package com.swak.converter;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import org.springframework.core.convert.converter.Converter;

import com.swak.utils.StringUtils;

/**
 * 转换 日期等
 * 
 * @author 618lf
 */
public class LocalTimeConverter implements Converter<String, LocalTime> {

	public static final String[] DATE_PATTERNS = { "HH:mm:ss", "HH:mm", "HH" };

	@Override
	public LocalTime convert(String source) {
		if (!StringUtils.isEmpty(source)) {

			// 获取日期
			String str = source.trim();

			// 日期的长度str.length()
			int length = str.length();

			/*
			 * 使用格式DATE_PATTERNS[0]
			 */
			if (length == 8) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERNS[0]);
				return LocalTime.parse(str, df);
			}

			/*
			 * 使用格式DATE_PATTERNS[1]
			 */
			else if (length == 5) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERNS[1]);
				return LocalTime.parse(str, df);
			}

			/*
			 * 使用格式DATE_PATTERNS[3]
			 */
			else if (length == 2) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERNS[2]);
				return LocalTime.parse(str, df);
			}
		}
		return null;
	}
}
